package artid.com.arttogo.view.alphabeticalindex;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.TextView;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import artid.com.arttogo.R;
import artid.com.arttogo.activity.BaseActivity;

/**
 * 
 *    
 * 项目名称：ArtworkArt   
 * 类名称：AlphabeticalIndex_Activity   
 * 类描述：字母索引   
 * 创建人：耿卫斌   
 * 创建时间：2017-2-24 下午3:38:46   
 *
 */
public class AlphabeticalIndex_Activity extends BaseActivity {
	private Context mContext;
	private ListView mListView;
	// 右侧A-Z字母列表
	private MyLetterAlistView letterListView;
	// dialog text
	private TextView overlay;
	// 估计是弹出dialog线程
	private OverlayThread overlayThread;
	//机构Adapter
	private IndexesMechanism_Adapter adapter;
	private Handler handler;
	/**
	 * 汉字转换成拼音的类
	 */
	private List<IndexesMechanismBean> dateList;
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator_Mechanism pinyinComparator;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_alphabeticalindex);
		initView();
	}

	private void initView(){
		mContext=AlphabeticalIndex_Activity.this;
		handler = new Handler();
		overlayThread = new OverlayThread();
		mListView = (ListView) findViewById(R.id.AlphabeticalIndex_ListView);
		letterListView = (MyLetterAlistView) findViewById(R.id.AlphabeticalIndex_MyLetterAlistView);
		/** 给ListView设置adapter **/
		// 根据拼音排序
		pinyinComparator = new PinyinComparator_Mechanism();
		dateList = new ArrayList<IndexesMechanismBean>();
		dateList=filledData(setData());
		Collections.sort(dateList, pinyinComparator);// 根据a-z进行排序源数据
		adapter = new IndexesMechanism_Adapter(mContext, dateList);
		mListView.setAdapter(adapter);
		initOverlay();
		letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
	}

	/**
	 * 设置数据
	 * @return
	 */
	private List<IndexesMechanismBean> setData(){
		List<IndexesMechanismBean> list=new ArrayList<IndexesMechanismBean>();
		IndexesMechanismBean bean11=new IndexesMechanismBean();
		bean11.setName("码的");
		list.add(bean11);
		IndexesMechanismBean bean12=new IndexesMechanismBean();
		bean12.setName("牛逼");
		list.add(bean12);
		IndexesMechanismBean bean13=new IndexesMechanismBean();
		bean13.setName("噢啦");
		list.add(bean13);
		IndexesMechanismBean bean14=new IndexesMechanismBean();
		bean14.setName("日你妹");
		list.add(bean14);
		IndexesMechanismBean bean15=new IndexesMechanismBean();
		bean15.setName("死了");
		list.add(bean15);
		IndexesMechanismBean bean16=new IndexesMechanismBean();
		bean16.setName("讨论");
		list.add(bean16);
		IndexesMechanismBean bean17=new IndexesMechanismBean();
		bean17.setName("王大大");
		list.add(bean17);
		IndexesMechanismBean bean18=new IndexesMechanismBean();
		bean18.setName("习大大");
		list.add(bean18);
		IndexesMechanismBean bean19=new IndexesMechanismBean();
		bean19.setName("晕了");
		list.add(bean19);
		IndexesMechanismBean bean20=new IndexesMechanismBean();
		bean20.setName("张大大");
		list.add(bean20);
		IndexesMechanismBean bean21=new IndexesMechanismBean();
		bean21.setName("…………");
		list.add(bean21);

		IndexesMechanismBean bean=new IndexesMechanismBean();
		bean.setName("阿哥");
		list.add(bean);
		IndexesMechanismBean bean1=new IndexesMechanismBean();
		bean1.setName("斌哥");
		list.add(bean1);
		IndexesMechanismBean bean2=new IndexesMechanismBean();
		bean2.setName("畅哥");
		list.add(bean2);
		IndexesMechanismBean bean3=new IndexesMechanismBean();
		bean3.setName("弟弟");
		list.add(bean3);
		IndexesMechanismBean bean4=new IndexesMechanismBean();
		bean4.setName("二哥");
		list.add(bean4);
		IndexesMechanismBean bean5=new IndexesMechanismBean();
		bean5.setName("房祖名");
		list.add(bean5);
		IndexesMechanismBean bean6=new IndexesMechanismBean();
		bean6.setName("哥哥");
		list.add(bean6);
		IndexesMechanismBean bean7=new IndexesMechanismBean();
		bean7.setName("猴子");
		list.add(bean7);
		IndexesMechanismBean bean8=new IndexesMechanismBean();
		bean8.setName("姐姐");
		list.add(bean8);
		IndexesMechanismBean bean9=new IndexesMechanismBean();
		bean9.setName("靠你");
		list.add(bean9);
		IndexesMechanismBean bean10=new IndexesMechanismBean();
		bean10.setName("类似");
		list.add(bean10);
		return list;
	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	private List<IndexesMechanismBean> filledData(List<IndexesMechanismBean> date) {
		List<IndexesMechanismBean> mList = new ArrayList<IndexesMechanismBean>();
		for (int i = 0; i < date.size(); i++) {
			IndexesMechanismBean mBean = new IndexesMechanismBean();
			mBean.setName(date.get(i).getName());
			// 汉字转换成拼音
			String pinyin=getFirstSpell(date.get(i).getName());
			try {
				String sortString = pinyin.substring(0, 1).toUpperCase(Locale.CHINESE);
				// 正则表达式，判断首字母是否是英文字母
				if (sortString.matches("[A-Z]")) {
					mBean.setSortLetters(sortString.toUpperCase());
				} else {
					mBean.setSortLetters("#");
				}
			} catch (Exception e) {
				// TODO: handle exception
				//当遇到非法字符的时候会出现报错的问题，所以直接将他设置为#状态
				mBean.setSortLetters("#");
			}

			mList.add(mBean);
		}
		return mList;

	}

	// 右侧A-Z字母监听
	private class LetterListViewListener implements MyLetterAlistView.OnTouchingLetterChangedListener {

		@Override
		public void onTouchingLetterChanged(final String s) {
			// 该字母首次出现的位置
			int position = adapter.getPositionForSection(s.charAt(0));
			if (position != -1) {
				mListView.setSelection(position);
				overlay.setText(dateList.get(position).getSortLetters());
				overlay.setVisibility(View.VISIBLE);
				handler.removeCallbacks(overlayThread);
				// 延迟一秒后执行，让overlay为不可见
				handler.postDelayed(overlayThread, 500);
			}
		}
	}

	// 初始化汉语拼音首字母弹出提示框
	private void initOverlay() {
		LayoutInflater inflater = LayoutInflater.from(AlphabeticalIndex_Activity.this);
		overlay = (TextView) inflater.inflate(R.layout.view_overlay, null);
		overlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
				| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		WindowManager windowManager = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);
	}

	// 设置overlay不可见
	private class OverlayThread implements Runnable {

		@Override
		public void run() {
			overlay.setVisibility(View.GONE);
		}

	}

	/**
	 * 汉字转换为汉语拼音首字母
	 * @param chines汉字
	 * @return 拼音
	 */
	public static String getFirstSpell(String chinese) {
		StringBuffer pybf = new StringBuffer();
		char[] arr = chinese.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (char curchar : arr) {
			if (curchar > 128) {
				try {
					String[] temp = PinyinHelper.toHanyuPinyinStringArray(curchar, defaultFormat);
					if (temp != null) {
						pybf.append(temp[0].charAt(0));
					}
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {
				pybf.append(curchar);
			}
		}
		return pybf.toString().replaceAll("\\W", "").trim();
	}



	/**
	 * 解析sort_key,封装简拼,全拼
	 * @param sortKey
	 * @return
	 */
	String chReg = "[\\u4E00-\\u9FA5]+";//中文字符串匹配
	public AlphabeticalIndexParse parseSortKey(String sortKey) {
		AlphabeticalIndexParse token = new AlphabeticalIndexParse();
		if (sortKey != null && sortKey.length() > 0) {
			//其中包含的中文字符
			String[] enStrs = sortKey.replace(" ", "").split(chReg);
			for (int i = 0, length = enStrs.length; i < length; i++) {
				if (enStrs[i].length() > 0) {
					//拼接简拼
					token.simpleSpell += enStrs[i].charAt(0);
					token.wholeSpell += enStrs[i];
				}
			}
		}
		return token;
	}
}
